package de.pernpas.stadtfuehrer.managedbean;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import de.pernpas.stadtfuehrer.entity.Role;
import de.pernpas.stadtfuehrer.entity.User;
import de.pernpas.stadtfuehrer.service.RoleService;
import de.pernpas.stadtfuehrer.service.RoleServiceImpl;
import de.pernpas.stadtfuehrer.service.UserService;
import de.pernpas.stadtfuehrer.service.UserServiceImpl;

@ManagedBean
@SessionScoped
public class UserMB {

	private User currentUser;
	private List<String> roleSelectedItems;
	private List<String> roleSelectItems;
	UserService us;
	private List<User> userList;
	
	public String editUser(){
		setRoleSelectItems(new ArrayList<String>());
		
		RoleService rs = new RoleServiceImpl();
		for (Role r: rs.getAllRoles() ) {
			getRoleSelectItems().add(r.name());
		}
		return "/resources/pages/admin/editUser.xhtml";
	}

	public User getCurrentUser() {
		return currentUser;
	}

	public List<String> getRoleSelectedItems() {
		return roleSelectedItems;
	}

	public List<String> getRoleSelectItems() {
		return roleSelectItems;
	}

	public List<User> getUserList() {
		return userList;
	}
	
	@PostConstruct
	public void init(){
		if(us == null) us = new UserServiceImpl();
		setUserList(us.retrieveAllUser());
	}
	
	public void setCurrentUser(User currentUser) {
		this.currentUser = currentUser;
	}

	public void setRoleSelectedItems(List<String> roleSelectedItems) {
		this.roleSelectedItems = roleSelectedItems;
	}

	public void setRoleSelectItems(List<String> roleSelectItems) {
		this.roleSelectItems = roleSelectItems;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public String updateUser(){
		List<Role> roles = new ArrayList<Role>();
		for (String s : roleSelectedItems) {
			roles.add(Role.getRole(s));
		}
		currentUser.setRoles(roles);
		us.update(currentUser);
		init();
		return "/resources/pages/admin/user.xhtml";
	}
}
